package com.akk.module.authentication.utils;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

public class HttpRequestClient {

    public HttpRequestClient() {
    }

    public static String invoke_https(String url, List<NameValuePair> parameters, String charSet) throws Exception {
        HttpClient client = WebClientDevWrapper.wrapClient(new DefaultHttpClient());
        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, charSet);
        formEntity.setContentEncoding(charSet);
        formEntity.getContentEncoding();
        httpPost.setEntity(formEntity);
        HttpResponse httpResponse = client.execute(httpPost);
        InputStream contentInputStream = httpResponse.getEntity().getContent();
        String data = new String(readAll(contentInputStream));
        return data;
    }

    public static String invoke_http(String url, List<NameValuePair> parameters, String charSet) throws Exception {
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, charSet);
        formEntity.setContentEncoding(charSet);
        formEntity.getContentEncoding();
        httpPost.setEntity(formEntity);
        HttpResponse httpResponse = client.execute(httpPost);
        InputStream contentInputStream = httpResponse.getEntity().getContent();
        String data = new String(readAll(contentInputStream));
        return data;
    }

    public static byte[] readAll(InputStream is) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        boolean len = true;

        int len1;
        while((len1 = is.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len1);
        }

        outSteam.close();
        is.close();
        return outSteam.toByteArray();
    }
}
